package fr.upmc.tps.mdoc.servlets;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import fr.upmc.tps.mdoc.domain.DAOUser;
import fr.upmc.tps.mdoc.models.User;

/**
 * Servlet implementation class NewUser
 */
public class NewUser extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public NewUser() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		request.getRequestDispatcher("pages/addUser.jsp").forward(request,
				response);

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		DAOUser daou = new DAOUser();

		String login = request.getParameter("user");
		String passwd = request.getParameter("passwd");

		User user = new User(login, passwd);

		if (daou.addUser(user)) {

			request.getSession().setAttribute("existuser", true);
			request.getSession().setAttribute("user", user);

			request.getRequestDispatcher("pages/accueil.jsp").forward(request,
					response);
		} else {

			request.getSession().setAttribute("existuser", false);

			request.getRequestDispatcher("pages/index.jsp").forward(request,
					response);
		}

	}

}
